package bioAndNio.nio;

import com.sun.deploy.ui.DialogTemplate;
import com.sun.net.httpserver.HttpHandler;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * \* User: Administrator
 * <p>
 * \* Date: 2020/9/27
 * <p>
 * \* Time: 14:09
 * <p>
 * \* Description:
 * \
 */
public class HttpServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress(8088));
        ssc.configureBlocking(false);
        //为ssc注册选择器
        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            if (selector.select(3000) == 0) {
                continue;
            }
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey next = iterator.next();
                new Thread(new HttpHandler(next)).run();
                iterator.remove();
            }
        }
    }

    public static class HttpHandler implements Runnable {
        private int bufferSize = 1024;
        private String localCharset = "UTF-8";
        private SelectionKey key;

        public HttpHandler(SelectionKey key) {
            this.key = key;
        }

        public void handleAccept() throws IOException {
            SocketChannel clientChannel = ((ServerSocketChannel) key.channel()).accept();
            clientChannel.configureBlocking(false);
            clientChannel.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize));
        }

        public void handleRead() throws IOException {
            SocketChannel sc = (SocketChannel) key.channel();
            ByteBuffer buffer = (ByteBuffer) key.attachment();
            buffer.clear();
            if (sc.read(buffer) == -1) {
                sc.close();
            } else {
                buffer.flip();
                String receiveStr = Charset.forName(localCharset).newDecoder().decode(buffer).toString();
                String[] reqMesg = receiveStr.split("\r\n");
                for (String s : reqMesg) {
                    System.out.println(s);
                    if (s.isEmpty()) {
                        break;
                    }
                }
                String[] firstLine = reqMesg[0].split(" ");
                System.out.println("Method:\t" + firstLine[0]);
                System.out.println("url:\t" + firstLine[1]);
                System.out.println("HTTP Version:\t" + firstLine[2]);

                StringBuilder respStr = new StringBuilder();
                respStr.append("HTTP/1.1 200 OK\r\n");
                respStr.append("Content-Type:text/html;charset" + localCharset + "\r\n");
                respStr.append("\r\n");
                respStr.append("<html><head><title>显示报文</title></head><body>");
                respStr.append("接受到的报文：<br/>");
                for (String s : reqMesg) {
                    respStr.append(s + "<br/>");
                }
                respStr.append("</body></html>");
                buffer = ByteBuffer.wrap(respStr.toString().getBytes(localCharset));
                sc.write(buffer);
                sc.close();
            }
        }


        @Override
        public void run() {
            try {
                if (key.isAcceptable()) {
                    handleAccept();
                }
                if (key.isReadable()) {
                    handleRead();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}